# app/routers/file_router.py
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Response
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.services.file_service import FileService
from app.schemas.file_schema import FileOut
from app.schemas.common_schema import R

router = APIRouter(prefix="/files", tags=["文件"])

@router.post("/spot/{spot_id}/upload", response_model=R[FileOut])
def upload_spot_file(
    spot_id: int,
    file: UploadFile = File(...),
    biz_type: str = Form("SPOT_COVER"),
    db: Session = Depends(get_db),
):
    if biz_type not in {"SPOT_COVER", "SPOT_VIDEO"}:
        raise HTTPException(400, "biz_type 只能为 SPOT_COVER 或 SPOT_VIDEO")
    content = file.file.read()          # 同步读取
    code, msg, record = FileService.save_file(db, biz_type, spot_id, file.filename, content)
    if record:
        return R(code=code, message=msg, data=record)
    raise HTTPException(status_code=code, detail=msg)

@router.get("/{file_id}")
def access_file(file_id: int, db: Session = Depends(get_db)):
    record = FileService.get_file(db, file_id)
    if not record:
        raise HTTPException(404, "文件不存在")
    media_type = "image/jpeg" if record.biz_type == "SPOT_COVER" else "video/mp4"
    return Response(content=record.blob_data, media_type=media_type)